/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model2;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.net.URL;
import java.net.URI;
import java.util.regex.*;

/**
 *
 * @author Dustin
 */
public class WebPage extends WebObject {

    public WebPage(URL url, byte[] content) {
        super(url, content);
    }

    public List<URL> getLocalLinks() throws IOException {
        Parser p = new Parser(content, url);
        ArrayList<URL> l = new ArrayList<URL>();
        l.addAll(p.getLinks());
        l.addAll(p.getImages());
        return filterOutNonLocal(l);
    }

    private List<URL> filterOutNonLocal(List<URL> lijst) {
        List<URL> retval = new ArrayList<URL>();
        for (URL u : lijst) {
            if (isLocal(u)) {
                retval.add(u);
            }
        }
        return retval;
    }

    private boolean isLocal(URL u) {
        return (u.getHost().equals(url.getHost()));
    }

    @Override
    public void writeToFile() {
        String[] lines = new String(content).split("\n");
        String newContent = "";

        for (String s : lines) {

            Pattern p = Pattern.compile("(.*)(href|src)(=\")(.*?)(\".*)");
            Matcher m = p.matcher(s);

            if (m.matches()) {
                m.reset();

                while (m.find()) {
                    String theLink = "";
                    try {
                        URI link = new URI(m.group(4));
                        if (link.isAbsolute()) {
                            link = url.toURI().relativize(link);
                            theLink = link.toString().replaceFirst("^/", "");
                        } else {
                            theLink = link.toString().replaceFirst("^/", "");
                        }
                    } catch (Exception ex) {
                        System.err.println("Cannot create URI from link " + m.group(4));
                        theLink = m.group(4);
                    }
                    newContent += m.group(1) + m.group(2) + m.group(3) + theLink + m.group(5) + "\n";
                }
            } else {
                newContent += s + "\n";
            }
        }
        content = newContent.getBytes();
    }
}
